/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.pays.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.DiscountType;
import com.qinyeit.serviceapp.entity.enums.UseScene;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.pays.DiscountBranchRepository;
import com.qinyeit.serviceapp.service.branchs.BranchDataReleasedServiceImpl;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.pays.DiscountDetailService;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.qinyetech.springstage.core.service.BaseService;
import com.qinyeit.serviceapp.repository.pays.DiscountPlanRepository;
import com.qinyeit.serviceapp.service.pays.DiscountPlanService;

import java.util.Date;
import java.util.List;

/** 
 * ClassName: DiscountPlanServiceImpl <br/> 
 * Function: 折扣方案 业务实现 <br/> 
 * date: 2018-11-29 09:56:09 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class DiscountPlanServiceImpl extends BaseService<DiscountPlan, Long> implements DiscountPlanService {


	@Autowired
	private DiscountPlanRepository discountPlanRepository;
	@Autowired
	private DiscountDetailService discountDetailService;
	@Autowired
	private BranchService branchService;
	@Autowired
	private DiscountBranchRepository discountBranchRepository;
	@Autowired
	private BranchDataReleasedServiceImpl branchDataReleasedService;

	@Override
	public void saveData(JSONObject data, Long merchantGroupId, String operator) {
		JSONObject plansData =data.getJSONObject("discountPlans");
		JSONArray dishesCountData =data.getJSONArray("dishesCount");
		if(plansData==null){
			throw new BusinessRunTimeException("请填写折扣信息",10001);
		}
		Long id = plansData.getLong("id");
		DiscountPlan discountPlan = null;
		if(id!=null){
			discountPlan = this.findById(id);
			discountPlan.setUpdateTimestamp(DateUtils.current());
			if(discountPlan.getType()==DiscountType.PLAN){
				//删除折扣明细
				discountPlanRepository.deleteDetails(discountPlan.getId());
			}
		}else {
			discountPlan = new DiscountPlan();
			discountPlan.setUuid(LocalUtils.getUUID());
			discountPlan.setUpdateTimestamp(DateUtils.current());
			discountPlan.setType(DiscountType.valueOf(plansData.getString("type")));
			if(discountPlan.getType()==DiscountType.PLAN){
				//方案折扣
				discountPlan.setStoreId(plansData.getLong("storeId"));
			}else if (discountPlan.getType()==DiscountType.AllSINGLE){
				//全单折扣
				discountPlan.setDiscount(plansData.getDouble("discount"));

			}
		}
		if(StringUtils.isBlank(plansData.getString("startTime")) || StringUtils.isBlank(plansData.getString("endTime"))){
			throw new BusinessRunTimeException("请选择有效日期",10002);
		}
		if(StringUtils.isBlank(plansData.getString("name"))){
			throw new BusinessRunTimeException("请填写折扣名称",10003);
		}
		discountPlan.setName(plansData.getString("name"));
		discountPlan.setStartTime(DateUtils.parse(plansData.getString("startTime")));
		discountPlan.setEndTime(DateUtils.parse(plansData.getString("endTime")));
//		discountPlan.setHasVip(plansData.getBoolean("hasVip"));
		discountPlan.setUseScene(UseScene.valueOf(plansData.getString("useScene")));
		discountPlan.setMerchantGroupId(merchantGroupId);
		discountPlan.setOperateTime(new Date());
		discountPlan.setOperatorName(operator);
		discountPlan.setSpecialDiscount(plansData.getDouble("specialDiscount"));
		discountPlan = this.update(discountPlan);

		if (discountPlan.getType()==DiscountType.PLAN){
			if(CollectionUtils.isNotEmpty(dishesCountData)){
				JSONObject item;
				DiscountDetail detail = null;
				for (int i = 0; i < dishesCountData.size(); i++) {
					item = dishesCountData.getJSONObject(i);
					detail = new DiscountDetail();
					detail.setCategoryId(item.getLong("categoryId"));
					detail.setDishesId(item.getLong("dishesId"));
					detail.setRate(item.getDouble("rate"));
					detail.setDiscountId(discountPlan.getId());
					detail.setMerchantGroupId(merchantGroupId);
					detail.setSpecialRate(item.getDouble("specialRate"));
					discountDetailService.save(detail);
				}
			}
		}


	}

	@Override
	public void allocationBranchSave(JSONObject data) {
		JSONArray ids = data.getJSONArray("ids");
		JSONArray branchIds = data.getJSONArray("branchs");
		if(CollectionUtils.isEmpty(ids)){
			throw new BusinessRunTimeException("请选择方案折扣",10001);
		}

		if(CollectionUtils.isEmpty(branchIds)){
			throw new BusinessRunTimeException("分店不能为空",10003);
		}
		DiscountPlan discountPlan = null;
		Branch branch = null;
		DiscountBranch discountBranch = null;
		List<DiscountBranch> discountBranchList = Lists.newArrayList();
		List<DiscountPlan> planList = Lists.newArrayList();
		for (int i = 0; i < ids.size(); i++) {
			discountPlan = this.findById(ids.getLong(i));
			if(discountPlan==null){
				throw new BusinessRunTimeException("选择的折扣方案不存在",10004);
			}
			planList.add(discountPlan);
			//先删除以前的分店信息
			discountPlanRepository.deleteBranchs(discountPlan.getId());

			for (int n = 0;n < branchIds.size(); n++) {
				branch = branchService.findById(branchIds.getLong(n));
				if(branch==null){
					throw new BusinessRunTimeException("门店不存在",10005);
				}
				discountBranch = new DiscountBranch();
				discountBranch.setBranchId(branchIds.getLong(n));
				discountBranch.setDiscountId(discountPlan.getId());
				discountBranch.setDistrictId(branch.getDistrictId());
				discountBranch.setMerchantGroupId(discountPlan.getMerchantGroupId());
				discountBranchList.add(discountBranch);
			}
		}
		discountBranchRepository.saveAll(discountBranchList);

		List<Long> bIDs = branchIds.toJavaList(Long.class);
		branchDataReleasedService.updateDiscountPlan(bIDs,planList,planList.get(0).getMerchantGroupId());

	}

	@Override
	public Long branchUseCountForDiscountPlan(DiscountPlan plan) {
		return branchDataReleasedService.branchUseCountForDiscountPlan(plan);
	}

	@Override
	public void deleteBranchDiscountPlanData(DiscountPlan plan) {
		branchDataReleasedService.deleteBranchDiscountPlanData(plan);
	}
}